package tbalert.web.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import tbalert.hibernate3.Updater;
import tbalert.page.Pagination;
import tbalert.page.SimplePage;
import tbalert.session.SessionProvider;
import tbalert.web.PwdEncoder;
import tbalert.web.ResponseUtils;
import tbalert.web.SysConstants;
import tbalert.web.WebErrors;
import tbalert.web.entity.Dwdm;
import tbalert.web.manager.DwdmMng;
import tbalert.web.manager.RoleMng;

@Controller
@RequestMapping(value = "/admin/dwdm")
public class DwdmAct {
	private static final Logger log = LoggerFactory.getLogger(DwdmAct.class);

	@RequestMapping(value = "/list.do")
	public String list(ModelMap model, HttpServletRequest request, Dwdm dwdm, Integer pageSize,
			Integer pageNo) {
		Dwdm bean = (Dwdm) session.getAttribute(request, SysConstants.DWDM_KEY);
		String sjdw = bean.getDwid();
		if(!StringUtils.isBlank(sjdw) && sjdw.equals("bssa")){
			sjdw="00";
		}
		dwdm.setDwid(sjdw);
		if (pageSize == null) {
			pageSize = SimplePage.DEF_COUNT;
		}
		if (pageNo == null) {
			pageNo = 1;
		}
		Pagination p = dwdmMng.find(dwdm, pageNo, pageSize);
		model.put("pagination", p);
		model.put("dwdm", dwdm);
		model.put("roles", roleMng.getAll());
		return "/admin/dwdm/list";
	}

	@RequestMapping(value = "/add.do")
	public String add(ModelMap model, HttpServletRequest request) {
		Dwdm dwdm = (Dwdm) session.getAttribute(request, SysConstants.DWDM_KEY);
		String sjdw = dwdm.getDwid();
		if(!StringUtils.isBlank(sjdw) && sjdw.equals("bssa")){
			sjdw="00";
		}
		model.put("sjdws", dwdmMng.findBySjdw(sjdw));
		model.put("roles", roleMng.getAll());
		return "/admin/dwdm/add";
	}

	@RequestMapping(value = "/edit.do")
	public String edit(ModelMap model, HttpServletRequest request, String id) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		model.put("dwdm", dwdmMng.findById(id));
		String sjdwid = StringUtils.left(id, id.length() - 2);
		if (StringUtils.isBlank(sjdwid)) {
			sjdwid = "00";
		}
		Dwdm d = dwdmMng.findById(sjdwid);
		if (d != null) {
			model.put("sjdwmc", d.getDwmc());
		}
		model.put("roles", roleMng.getAll());
		return "/admin/dwdm/edit";
	}

	@RequestMapping(value = "/save.do")
	public String save(ModelMap model, HttpServletRequest request, Dwdm dwdm, String sjdwId) {
		dwdm.setDwid(dwdmMng.buildDwid(sjdwId));
		WebErrors errors = validateSave(dwdm, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		dwdm.setDlmm(pwdEncoder.encodePassword(SysConstants.PASSWORD));

		dwdmMng.save(dwdm);
		return "redirect:list.do";
	}

	@RequestMapping(value = "/update.do")
	public String update(ModelMap model, HttpServletRequest request, Dwdm dwdm) {
		WebErrors errors = validateUpdate(dwdm.getDwid(), dwdm.getDlmc(), request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		dwdm.setRole(roleMng.findById(dwdm.getRole().getId()));
		Updater<Dwdm> updater = new Updater<Dwdm>(dwdm);
		dwdmMng.update(updater);
		log.info("update dwdm id={}.", dwdm.getDwid());
		model.put(SysConstants.MESSAGE, "global.success");
		return list(model, request, new Dwdm(), SimplePage.DEF_COUNT, 1);
	}

	@RequestMapping(value = "/delete.do")
	public String delete(ModelMap model, HttpServletRequest request, String id) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		Dwdm dwdms = dwdmMng.disable(id);
		log.info("delete dwdm id={}.", dwdms.getDwid());
		return list(model, request, new Dwdm(), SimplePage.DEF_COUNT, 1);
	}

	@RequestMapping(value = "/enable.do")
	public String enable(ModelMap model, HttpServletRequest request, String id) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		Dwdm dwdms = dwdmMng.enable(id);
		log.info("delete dwdm id={}.", dwdms.getDwid());
		return list(model, request, new Dwdm(), SimplePage.DEF_COUNT, 1);
	}

	@RequestMapping(value = "/vldDlmc.do")
	public void vldDlmc(HttpServletRequest request, HttpServletResponse response, String dlmc)
			throws JSONException {
		JSONObject json = new JSONObject();
		if (StringUtils.isBlank(dlmc) || dwdmMng.dlmcExist(dlmc)) {
			json.put("success", false);
		} else {
			json.put("success", true);
		}
		ResponseUtils.renderJson(response, json.toString());
	}

	@RequestMapping(value = "/resetDlmm.do")
	public void resetDlmm(HttpServletRequest request, HttpServletResponse response, String dwid)
			throws JSONException {
		JSONObject json = new JSONObject();
		Dwdm bean = (Dwdm) session.getAttribute(request, SysConstants.DWDM_KEY);
		if (bean.getRole().getAdmin()) {
			dwdmMng.resetDlmm(dwid);
			json.put("msg", "初始化登录密码成功。");
		} else {
			json.put("msg", "你没有重置登录密码的权限");
		}
		ResponseUtils.renderJson(response, json.toString());
	}

	@Autowired(required = true)
	private DwdmMng dwdmMng;
	@Autowired(required = true)
	private RoleMng roleMng;
	@Autowired(required = true)
	private SessionProvider session;
	@Autowired(required = true)
	private PwdEncoder pwdEncoder;

	private WebErrors validateSave(Dwdm bean, HttpServletRequest request) {
		WebErrors errors = new WebErrors(request);
		if (dwdmMng.findById(bean.getDwid()) != null) {
			errors.addErrorCode("error.dwidDuplicate", bean.getDwid());
		}
		return errors;
	}

	private WebErrors validateEdit(String id, HttpServletRequest request) {
		WebErrors errors = new WebErrors(request);
		if (vldExist(id, errors)) {
			return errors;
		}
		return errors;
	}

	private WebErrors validateUpdate(String id, String dlmc, HttpServletRequest request) {
		WebErrors errors = new WebErrors(request);
		if (vldExist(id, errors)) {
			return errors;
		}
		return errors;
	}

	private boolean vldExist(String id, WebErrors errors) {
		if (errors.ifNull(id, "id")) {
			return true;
		}
		Dwdm entity = dwdmMng.findById(id);
		if (errors.ifNotExist(entity, Dwdm.class, id)) {
			return true;
		}
		return false;
	}
}
